<!-- 对el-form二次封装 -->
<template>
  <div id="myform">
    <!-- 标题 -->
    <slot name="header"></slot>
    <!-- 表单 -->
    <el-form :label-width="props.formLabelWidth">
      <el-row>
        <template v-for="item in props.formItems" :key="item.field">
          <el-col v-bind="props.formStyle">
            <el-form-item v-bind="item" :style="props.itemStyle">
              <!-- 普通输入框 -->
              <template v-if="item.type === 'text' || item.type === 'password'">
                <el-input
                  v-bind="item.options"
                  :show-password="item.type === 'password'"
                  v-model="newFormData[`${item.field}`]"
                ></el-input>
              </template>
              <!-- textarea输入框 -->
              <template v-else-if="item.type === 'textarea'">
                <el-input
                  v-bind="item.options"
                  type="textarea"
                  v-model="newFormData[`${item.field}`]"
                ></el-input>
              </template>
              <!-- 选择器 -->
              <template v-else-if="item.type === 'select'">
                <el-select
                  style="width: 100%"
                  v-bind="item.options"
                  v-model="newFormData[`${item.field}`]"
                >
                  <el-option
                    v-for="optionItem in item.selectOptions"
                    :key="optionItem.value"
                    :label="optionItem.label"
                    :value="optionItem.value"
                  />
                </el-select>
              </template>
              <!-- 时间选择器 -->
              <template v-else-if="item.type === 'picker'">
                <el-date-picker
                  style="width: 100%"
                  v-bind="item.pickerOptions"
                  v-model="newFormData[`${item.field}`]"
                />
              </template>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <!-- 操作 -->
    <slot name="footer"></slot>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, withDefaults, defineEmits } from 'vue'
import type { FormItemsTypes } from './types'

interface PropsTypes {
  // 表单数据
  formData: any
  // 表单子项
  formItems: Array<FormItemsTypes>
  // 表单表头长度
  formLabelWidth?: string
  // 表单样式
  formStyle?: any
  // 表单子项样式
  itemStyle?: any
}

// 注册props
const props = withDefaults(defineProps<PropsTypes>(), {
  formLabelWidth: '80px',
  formStyle: () => {
    return {
      lg: 6,
      md: 8,
      sm: 12
    }
  },
  itemStyle: () => {
    return {
      padding: '10px 15px'
    }
  }
})

// 注册emits
const emits = defineEmits(['update:formData'])

const newFormData = ref<any>({ ...props.formData })

watch(
  () => newFormData.value,
  (newVal) => {
    emits('update:formData', newVal)
  },
  {
    deep: true
  }
)
</script>

<style scoped lang="less">
#myform {
  padding-top: 20px;
}
</style>
